package com.forum.framework.security.core.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.forum.framework.common.exception.ServiceException;
import com.forum.framework.common.pojo.DataResult;
import com.forum.framework.common.util.json.JsonUtils;
import com.forum.framework.common.util.servlet.ServletUtils;
import com.forum.framework.security.config.SecurityProperties;
import com.forum.framework.security.core.LoginUser;
import com.forum.framework.security.core.util.SecurityUtils;
import com.forum.framework.web.core.handler.GlobalExceptionHandler;
import com.forum.framework.web.core.util.WebFrameworkUtils;
import com.forum.module.system.api.oauth2.OAuth2TokenApi;
import com.forum.module.system.api.oauth2.dto.OAuth2AccessTokenCheckRespDTO;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * Token 过滤器，验证 token 的有效性
 * 验证通过后，获得 {@link com.forum.framework.security.core.LoginUser} 信息，并加入到 Spring Security 上下文
 *
 * @author zihan.ouyang
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(TokenAuthenticationFilter.class);
    private final SecurityProperties securityProperties;

    private final OAuth2TokenApi oauth2TokenApi;

    private final GlobalExceptionHandler globalExceptionHandler;

    public TokenAuthenticationFilter(SecurityProperties securityProperties,
                                     OAuth2TokenApi oauth2TokenApi,
                                     GlobalExceptionHandler globalExceptionHandler) {
        this.securityProperties = securityProperties;
        this.oauth2TokenApi = oauth2TokenApi;
        this.globalExceptionHandler = globalExceptionHandler;
    }

    @Override
    @SuppressWarnings("NullableProblems")
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 情况一，基于 header[login-user] 获得用户，例如说来自 Gateway 或者其它服务透传
        LoginUser loginUser = buildLoginUserByHeader(request);

        // 情况二，基于 Token 获得用户
        // 注意，这里主要满足直接使用 Nginx 直接转发到 Spring Cloud 服务的场景。
        if (loginUser == null) {
            String token = SecurityUtils.getToken(request, securityProperties.getHeaderName(),
                    securityProperties.getTokenParameter());

            if (StrUtil.isNotEmpty(token)) {
                Integer userType = WebFrameworkUtils.getLoginUserType(request);
                try {
                    // 1.1 基于 token 构建登录用户
                    loginUser = buildLoginUserByToken(token, userType);
                } catch (Throwable ex) {
                    DataResult<?> result = globalExceptionHandler.allExceptionHandler(request, ex);
                    ServletUtils.writeJson(response, result);
                    return;
                }
            }
        }

        // 设置当前用户
        if (loginUser != null) {
            SecurityUtils.setLoginUser(loginUser, request);
        }
        filterChain.doFilter(request, response);
    }


    private LoginUser buildLoginUserByToken(String token, Integer loginUserType) {
        try {
            // 校验访问令牌
            OAuth2AccessTokenCheckRespDTO accessToken = oauth2TokenApi.checkAccessToken(token).getCheckedData();
            if (accessToken == null) {
                log.warn("Access token is null for token: {}", token);
                return null;
            }
            log.info("Access token checked successfully: {}", accessToken);
            // 用户类型不匹配，无权限
            // 注意：只有 /admin-api/* 和 /app-api/* 有 userType，才需要比对用户类型
            // 类似 WebSocket 的 /ws/* 连接地址，是不需要比对用户类型的
            if (loginUserType != null && ObjectUtil.notEqual(accessToken.getUserType(), loginUserType)) {
                throw new AccessDeniedException("错误的用户类型");
            }
            // 构建登录用户
            return new LoginUser().setUserId(accessToken.getUserId()).setUserType(accessToken.getUserType())
                    .setInfo(accessToken.getUserInfo()).setRoles(accessToken.getScopes())
                    .setExpireTime(accessToken.getExpiresTime());
        } catch (ServiceException serviceException) {
            log.error("Error checking access token: {}", token, serviceException);
            // 校验 Token 不通过时，考虑到一些接口是无需登录的，所以直接返回 null 即可
            return null;
        }
    }

    private LoginUser buildLoginUserByHeader(HttpServletRequest request) {
        String loginUserStr = request.getHeader(SecurityUtils.LOGIN_USER_HEADER);
        if (StrUtil.isEmpty(loginUserStr)) {
            return null;
        }
        try {
            loginUserStr = URLDecoder.decode(loginUserStr, StandardCharsets.UTF_8); // 解码，解决中文乱码问题
            return JsonUtils.parseObject(loginUserStr, LoginUser.class);
        } catch (Exception ex) {
            log.error("[buildLoginUserByHeader][解析 LoginUser({}) 发生异常]", loginUserStr, ex);
            throw ex;
        }
    }
}
